Grokking Scalable Systems for Interviews
Rate this course
Ask Author
Contribute
Back to course home

4% completed

Vote For New Content
Introduction
Course Overview
Who This Course Is for
Caching
What Is Negative Caching and When Should You Cache 404 or Empty Results?
What Is the Difference Between Soft TTL and Hard TTL, and Why Does It Matter?
How Can a Bloom Filter Reduce Cache or Database Load?
What Is Distributed Locking for Cache Rebuilds, and How Does It Prevent Cache Stampedes?
What Are Sticky Sessions (Session Affinity) and When Should I Avoid Them?
What Is the Difference between Liveness Checks and Readiness Checks in Load Balancers?
What is Global Server Load Balancing (GSLB) and How GeoDNS and Anycast Work?
What are the Main API Pagination Strategies (offset, cursor, keyset), and When Should I Use Each?
What are HTTP Conditional Requests (ETag, If‑None‑Match, Last‑Modified) and How They Reduce Load?
What Is the Difference between Rate Limiting and Throttling and Quotas?
What Are Idempotency Keys and How to Implement Them Safely for Payments
What are SQL Isolation Levels (Read Committed, Repeatable Read, Serializable), and What Anomalies Do They Prevent?
What Is a Write‑Ahead Log (WAL), and How Does It Ensure Durability?
What Is the Difference Between Synchronous and Asynchronous Replication, and When Should I Use Read Replicas?
What Is MVCC (Multi‑Version Concurrency Control), and How Does It Enable Concurrent Reads and Writes?
What Are Safe Patterns for Online Schema Changes vs. Offline Migrations?
What is Little’s Law and How to Use It for Quick Capacity Estimates in System Design
How Can I do Back-of-the-Envelope Sizing for QPS, Bandwidth, Storage, and Peak vs. Average Load?
What are Cold Starts and Warm Starts, and Why Do They Matter for Performance?
How Do I Choose a Good Shard Key and Avoid Hotspots (Bucketing and Key Randomization)?
What Are Range Sharding, Directory‑Based Sharding, and Geo‑Sharding, and What Are the Common Use Cases?
What Is the Difference Between Rendezvous Hashing and Consistent Hashing, and When Should I Use Each?
What Do At‑most‑once, At‑least‑once, And Exactly‑once Delivery Semantics Mean?
What Are Idempotent Producers And Consumers, And How Do De‑duplication Keys Work?
What Is Message Ordering, How Do Partition Keys Affect It, And When Can Ordering Break?
What Are Windowing And Watermarking In Streaming Systems, In Simple Terms?
What Is Quorum (N, R, W), And Why Does R + W > N Give Strongly Consistent Reads?
What Are Common Conflict Resolution Strategies (Last‑write‑wins, Vector Clocks, Logical Clocks)?
What Are Read Repair, Hinted Handoff, And Anti‑entropy (Merkle Trees) In Eventually Consistent Systems?
What Is The Difference Between SLI, SLO, And SLA, And Can You Give Simple Examples?
What Is Opentelemetry, And How Do Traces, Spans, Metrics, And Logs Fit Together?
What Is An Error Budget, And How Should It Guide Release Decisions?
What Are The Trade‑offs Between Server‑stored Sessions And JWTs for Authentication?
What Is The Difference Between TLS And MTLS, And When Is MTLS Appropriate For Service‑to‑service Auth?
What Is Secrets Management, And How Do Environment Variables, KMS, And Vault Compare?
What Is A Replay Attack, And How Is It Different from Idempotency Issues?
What Are The Differences Between TCP, UDP, And QUIC, And When Should I Use Each?
What Is The Difference Between A Forward Proxy, A Reverse Proxy, And NAT?
What Changed From HTTP/1.1 To HTTP/2 To HTTP/3, And What Are Head‑of‑line Blocking And Multiplexing?
What Is the Difference Between Content‑Addressable Storage and Location‑Based Addressing?
What Are Checksums and Etags, and How Do MD5/SHA Compare to CRC for Integrity?
What Are Hot, Warm, Cold, and Archive Storage Tiers, and When Should I Use Each?
What Is the Outbox Pattern, and How Does Change Data Capture (CDC) Work at a High Level?
What Is CQRS (Command Query Responsibility Segregation), and When Should I Consider It?
What Are the Differences Between a Circuit Breaker, Retry With Backoff, and Rate Limiting?
What Are RPO and RTO, and How Do They Differ in Disaster Recovery Planning?
What Is the Difference Between Active‑Active and Active‑Passive Architectures?
What Is Graceful Degradation, and How Do Feature Flags Help Availability?
What Are the Differences Between UUID, ULID, KSUID, and Snowflake IDs, and How Do I Choose?
How Do Snowflake‑Style IDs Work (Timestamp, Worker, Sequence), and What Problems Do They Solve?
What Is the Difference Between Wall‑Clock Time and Monotonic Time, and Why Is Clock Skew Hard?
Final Words
Key Takeaways
What To Learn Next
What Is Distributed Locking for Cache Rebuilds, and How Does It Prevent Cache Stampedes?

Distributed locking for cache rebuilds is a concurrency control technique that uses a shared lock (across servers or processes) to ensure only one request refreshes an expired cache item at a time, preventing multiple simultaneous recomputations (a cache stampede).

Understanding the Cache Stampede Problem

A cache stampede (also known as the dogpile effect or cache miss storm) occurs when a cached item expires and many processes try to rebuild it at once.

In high-traffic systems, if a popular cache entry becomes invalid, all concurrent requests that encounter the miss will fall back to the underlying data source (like a database) simultaneously.

This surge of identical queries can overwhelm the backend, causing a dramatic spike in load that slows down the application or even crashes it.

For example, one WordPress caching guide notes that when several processes all regenerate the same content at the same time, it results in a surge of SQL queries that can slow the site or even bring it to a halt.

In severe cases, none of the requests can complete because they contend for resources (a thundering herd), leading to cascading failures. This isn’t just theoretical. Facebook suffered a major outage in 2010 due to a cache stampede lasting four hours.

What Is Distributed Locking for Cache Rebuilds?

Distributed locking is a mechanism that acts like a mutex (mutual exclusion lock) but works across multiple processes or servers in a distributed system.

In the context of cache rebuilds, a distributed lock ensures that only one process (or server) at a time can recompute a given cached value when it expires.

All other concurrent requests for that same data must wait or use a fallback until the fresh value is ready, instead of each triggering a redundant rebuild.

Essentially, the first request to detect the cache miss “locks” the regeneration process, does the heavy work, and then releases the lock when done.

In practice, implementing a distributed lock often involves a shared external store (such as Redis, Memcached, or a database) to coordinate locks among nodes.

For instance, one common approach is using an atomic operation like Redis’s SETNX (set if not exists) to create a lock key: the first process sets a lock key in Redis and proceeds to recompute the data, while others find the lock key present and know another worker is handling the rebuild.

Once the data is recomputed and put into the cache, the lock key is deleted to let other requests use the new cached data. This way, all servers agree on who is performing the cache refresh at any moment.

Cache Lock Mechanism
Cache Lock Mechanism

How the Lock Mechanism Works (Step-by-Step)

To illustrate, here’s the typical cache rebuild flow with distributed locking:

  1. Cache Check: A request arrives and checks the cache for the data. If the data is present and not expired, it’s a cache hit and is returned immediately (no lock needed).

  2. Lock Acquisition: If the cache is missing or expired (cache miss), the process attempts to acquire a lock specific to that cache key (e.g. using a distributed mutex in Redis or a database). This lock is a signal that “recompute is in progress” for that item.

  3. Single Regeneration: The one request that successfully acquires the lock now becomes responsible for regenerating the cache. It goes to the original data source (for example, querying the database or an API) to fetch the fresh data. This is the only process doing the recomputation at this time.

  4. Cache Update: After fetching the up-to-date data, the process updates the cache with the new value and sets an appropriate TTL (time-to-live) on it. The expensive operation is now complete.

  5. Lock Release: The process releases the lock (e.g. deletes the lock key in Redis) as soon as the cache has been updated. Releasing the lock signals that other waiting requests can now proceed.

  6. Serving Waiting Requests: Any other requests that arrived during the regeneration phase will have been blocked from recomputing the value. These waiting requests can now read the freshly populated cache entry once the lock is released. In some implementations, those other requests might actively poll for the lock release or simply retry after a short delay; regardless, they do not trigger additional database load. All of them get the up-to-date data from cache, avoiding duplicate work.

By following this sequence, the system ensures that even under heavy concurrency, only one expensive rebuild happens for a given cache key, and it happens just once per expiration interval.

How Distributed Locks Prevent Cache Stampedes

The distributed locking approach directly prevents the “stampede” effect by serializing cache regeneration.

Instead of dozens of processes hammering the database at once, they funnel through a single regenerating process.

This has two key benefits:

  • Eliminating Duplicate Queries: Because only the lock-holder hits the database or backend, the system avoids the duplicate work and query surge that would have occurred from concurrent rebuild attempts. For example, imagine a cached report takes 3 seconds to generate and normally receives 10 requests per second. If that cache expires, up to 30 processes could try to generate the report in those 3 seconds, flooding the database with redundant load. With a distributed lock, only one process generates the report while the other 29 wait, resulting in a single database query instead of thirty. This dramatically reduces load and contention on the backend.

  • Maintaining Fast Response: The waiting requests might incur a slight delay (until the cache is refreshed), but this is usually far better for user experience than the site slowing to a crawl or failing under a stampede. Once the one process updates the cache, all other requests get a cache hit and fast response again. In effect, the cache quickly “fills up” after expiration and continues to absorb traffic. By ensuring that only one request regenerates data and others wait, distributed locks can prevent stampedes altogether, keeping the system stable under high concurrency.

In summary, distributed locking acts as a traffic controller for cache misses. It collapses many simultaneous miss-triggered requests into a single recomputation operation.

This protects the origin database or service from overload, thereby maintaining overall application performance and stability.

By avoiding the avalanche of parallel recomputations, the system sidesteps the cascade of failures that define a cache stampede.

Example Scenario

To make this concrete, consider a web application with multiple servers caching a popular piece of data (say, a homepage feed).

All servers check the cache before querying the database.

Now, suppose that cache entry expires at a moment when three servers (or threads) almost simultaneously receive requests for the feed.

Without a lock, each server would detect a miss and hit the database, leading to three identical expensive queries running at once.

Importance and Best Practices

For students and developers, understanding distributed cache locking is important because it is a common solution to a classic scaling problem.

In system design interviews or real production systems, you may be asked how to handle the scenario of heavy read load when a cache expires.

Using a distributed lock (sometimes called a “dogpile prevention” lock) is a go-to answer to ensure reliability and efficiency.

However, implementing distributed locks correctly comes with important considerations:

  • Correct Lock Usage: The locking mechanism itself must be robust. It introduces a small overhead (an extra write/read to the locking store per miss) and needs careful handling of edge cases. For example, you should set a lock timeout (TTL) so that if the process holding the lock crashes or stalls, the lock will eventually expire and not stay stuck forever. Choosing an appropriate TTL (long enough to cover the recompute time, but not too long) is critical to avoid deadlocks.

  • Per-Key Granularity: Locks should generally be per cache key rather than one global lock for the entire cache. A global lock would prevent simultaneous rebuilds of different items and hurt performance. Per-key locks (each data item has its own mutex) allow high concurrency across different cache entries, while still serializing access to each entry.

  • Handling Lock Contention: If a request can’t get the lock (because another process is already rebuilding), the application needs a strategy for that situation. Often the request will either wait (briefly) and retry, or serve a stale cache value (if available) to the user and let the background lock-holder finish the update. The waiting could be an active sleep + retry with backoff, or using an async callback, depending on the system design. The goal is to ensure those concurrent requests do not all pile onto the database.

  • Avoiding Deadlocks: Developers must ensure locks are always released even if errors occur during recomputation. Use try/finally blocks or atomic scripts (like a Redis Lua script to release only if you still own the lock) to avoid situations where a lock isn't released due to a crash. Additionally, monitoring and logging can help detect if locks are contended or stuck (e.g., if lock acquisition fails frequently, it indicates heavy contention).

By adhering to these best practices, distributed cache locking can be extremely effective. When implemented properly, it “can prevent stampedes altogether” and ensure a smoother, more responsive user experience even under high load.

It’s a proven technique used alongside other strategies (like cache pre-warming, staggered expirations, or serving stale data) to maintain cache efficiency.

Conclusion

Distributed locking for cache rebuilds is a vital strategy for preserving performance in cached systems under heavy load.

It guarantees that cache refreshes happen one-at-a-time across a cluster, which prevents the cascade of concurrent misses that would otherwise hammer your databases and degrade service.

This concept is key to building scalable applications and is often tested in interviews as a solution to the cache stampede problem.

By using distributed locks (e.g. via Redis or similar) and following best practices to manage those locks safely, you can confidently avoid cache stampedes and keep your caching layer robust and efficient.

How Can a Bloom Filter Reduce Cache or Database Load?
What Are Sticky Sessions (Session Affinity) and When Should I Avoid Them?
Mark as Completed

On this page

Understanding the Cache Stampede Problem

What Is Distributed Locking for Cache Rebuilds?

How the Lock Mechanism Works (Step-by-Step)

How Distributed Locks Prevent Cache Stampedes

Example Scenario

Importance and Best Practices

Conclusion